package com.mediatek.datatransfer;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.tecno.widget.Toast;
import com.mediatek.datatransfer.SDCardReceiver.OnSDCardStatusChangedListener;
import com.mediatek.datatransfer.utils.BackupFilePreview;
import com.mediatek.datatransfer.utils.BackupFileScanner;
import com.mediatek.datatransfer.utils.Constants;
import com.mediatek.datatransfer.utils.Constants.MessageID;
import com.mediatek.datatransfer.utils.FileUtils;
import com.mediatek.datatransfer.utils.MyLogger;
import com.mediatek.datatransfer.utils.SDCardUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import com.mediatek.datatransfer.R;
/**
 * @author mtk81330
 *
 */
public class RestoreTabFragment extends PreferenceFragment {

    private static final String CLASS_TAG = MyLogger.LOG_TAG + "/RestoreTabFragment";
    private static final int START_ACTION_MODE_DELAY_TIME = 100;
    private static final String STATE_DELETE_MODE = "deleteMode";
    private static final String STATE_CHECKED_ITEMS = "checkedItems";

    private ListView mListView;
    private BackupFileScanner mFileScanner;
    private Handler mHandler;

    /**
     * @return Handler
     */
    public Handler getmHandler() {
        return mHandler;
    }
    private ProgressDialog mLoadingDialog;
    private boolean mDeleteActionMode;
    private DeleteMenuMode mActionModeListener;
    OnSDCardStatusChangedListener mSDCardListener;
    private boolean mIsActive = false;
    private View mMenuBar;
    private ImageButton mFooterButton;
    private FrameLayout mFooterFL;
    private TextView mMenuSelectItems;
    private CheckBox mMenuSelectCheckBox;
    private int mRecordNum = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onCreate");
        addPreferencesFromResource(R.xml.restore_tab_preference);
        mActionModeListener = new DeleteMenuMode();
        View view = getActivity().findViewById(R.id.main_view);
        if(view == null){
        	getActivity().setContentView(R.layout.main_activity);
        }
        mMenuBar = getActivity().findViewById(R.id.custom_menu_bar);
        mFooterButton = (ImageButton)getActivity().findViewById(R.id.backup_bt_backcup);
        mFooterFL = (FrameLayout)getActivity().findViewById(R.id.backup_fl_backcup);
        mMenuSelectItems = (TextView)getActivity().findViewById(R.id.menu_select_items);
        View back = getActivity().findViewById(R.id.menu_action_back_ll);
        mMenuSelectCheckBox = (CheckBox)getActivity().findViewById(R.id.menu_all_select_box);
        View button = getActivity().findViewById(R.id.menu_trash_button);
        if(back != null){
        	back.setOnClickListener(mActionModeListener);
        }
        if(mMenuSelectCheckBox != null){
        	mMenuSelectCheckBox.setOnClickListener(mActionModeListener);
        }
        if(button != null){
        	button.setOnClickListener(mActionModeListener);
        }
        if(mFooterButton != null){
        	mFooterButton.setBackground(getActivity().getDrawable(R.drawable.ic_ellipse_red_bg));
        	mFooterButton.setImageResource(R.drawable.ic_menu_trash_holo_dark_am);
        	mFooterButton.setOnClickListener(mActionModeListener);
        }
        addEmptyFooterView();
    }
    
    private View mEmptyFooterGroupView;
    
    public void addEmptyFooterView(){
    	mEmptyFooterGroupView = getActivity().getLayoutInflater()
    			.inflate(R.layout.tecno_list_footer_view, null, false);
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onAttach");
    }

    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onActivityCreated"+savedInstanceState);
        init();
        //int padding = (int)getActivity().getResources().getDimension(R.dimen.tecno_backup_list_padding);
        getListView().setPadding(0, 0, 0, 0);
        if (savedInstanceState != null) {
            boolean isActionMode = savedInstanceState.getBoolean(STATE_DELETE_MODE, false);
            if (isActionMode) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() == null) {
                            return;
                        }
                        showDeleteMenu(true);
                        mActionModeListener.restoreState(savedInstanceState);
                    }
                }, START_ACTION_MODE_DELAY_TIME);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onDestroy");
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
        if (mFileScanner != null) {
            mFileScanner.setHandler(null);
        }
        unRegisteSDCardListener();
    }

    /**
     * onPause.
     */
    public void onPause() {
        super.onPause();
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onPasue");
        if (mFileScanner != null) {
            mFileScanner.quitScan();
        }
        mIsActive = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onResume");
        mIsActive = true;
        // refresh
        if (SDCardUtils.isSdCardAvailable(getActivity())) {
            startScanFiles();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onDetach");
    }

    /**
     * @param outState state
     */
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mDeleteActionMode) {
            outState.putBoolean(STATE_DELETE_MODE, true);
            mActionModeListener.saveState(outState);
        }
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if (preference instanceof RestoreCheckBoxPreference) {
            RestoreCheckBoxPreference p = (RestoreCheckBoxPreference) preference;
            if (!mDeleteActionMode) {
                Intent intent = p.getIntent();
                String fileName = intent.getStringExtra(Constants.FILENAME);
                File file = new File(fileName);
                if (file.exists()) {
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), R.string.file_no_exist_and_update,
                            Toast.LENGTH_SHORT).show();
                }
            } else if (mActionModeListener != null) {
                mActionModeListener.setItemChecked(p, !p.isChecked());
            }
        }
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: onStart");
    }

    private void init() {
        initHandler();
        initListView(getView());
        initLoadingDialog();
        registerSDCardListener();
    }

    private void unRegisteSDCardListener() {
        if (mSDCardListener != null) {
            SDCardReceiver receiver = SDCardReceiver.getInstance();
            receiver.unRegisterOnSDCardChangedListener(mSDCardListener);
        }
    }

    private void registerSDCardListener() {
        mSDCardListener = new OnSDCardStatusChangedListener() {
            @Override
            public void onSDCardStatusChanged(final boolean mount) {
                if (mIsActive) {
                    if (!mount) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {

                                PreferenceScreen ps = getPreferenceScreen();
                                ps.removeAll();
                                // fix bug for ALPS01895396 start
                                try {
                                    Toast.makeText(getActivity(),
                                            R.string.nosdcard_notice,
                                            Toast.LENGTH_SHORT).show();
                                } catch (NullPointerException e) {
                                    e.printStackTrace();
                                }
                                // end
                            }
                        });
                        getActivity().finish();
                    }
                }
            }
        };

        SDCardReceiver receiver = SDCardReceiver.getInstance();
        receiver.registerOnSDCardChangedListener(mSDCardListener);
    }

    private void initLoadingDialog() {
        mLoadingDialog = new ProgressDialog(getActivity());
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.setMessage(getString(R.string.loading_please_wait));
        mLoadingDialog.setIndeterminate(true);
    }
    private TextView mEmptyView;
    private void initListView(View root) {
        View view = root.findViewById(android.R.id.list);
        if (view != null && view instanceof ListView) {
            mListView = (ListView) view;
            mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> listView, View view, int position,
                        long id) {
                	if(!mDeleteActionMode){
                		showDeleteMenu(true);
                	}
                    mActionModeListener.onPreferenceItemClick(getPreferenceScreen(), position);
                    return true;
                }
            });
        }
        mEmptyView = new TextView(getActivity());
        mEmptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
        mEmptyView.setGravity(Gravity.CENTER);
        mEmptyView.setVisibility(View.GONE);
        ((ViewGroup) getListView().getParent()).addView(mEmptyView);
        getListView().setEmptyView(mEmptyView);
    }

    @SuppressWarnings("unchecked")
    private void startDeleteItems(final HashSet<String> deleteItemIds) {
        PreferenceScreen ps = getPreferenceScreen();
        int count = ps.getPreferenceCount();
        HashSet<File> files = new HashSet<File>();
        for (int position = 0; position < count; position++) {
            Preference preference = ps.getPreference(position);
            if (preference != null && preference instanceof RestoreCheckBoxPreference) {
                RestoreCheckBoxPreference p = (RestoreCheckBoxPreference) preference;
                String key = p.getKey();
                if (deleteItemIds.contains(key)) {
                    files.add(p.getAccociateFile());
                }
            }
        }
        DeleteCheckItemTask deleteTask = new DeleteCheckItemTask();
        deleteTask.execute(files);
        ps.removeAll();
    }

    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(final Message msg) {
                switch (msg.what) {

                case MessageID.SCANNER_FINISH:
                    MyLogger.logD(CLASS_TAG, "recieve MessageID.SCANNER_FINISH");
                    if (getActivity() != null) {
                        addScanResultsAsPreferences(msg.obj);
                    }
                    MyLogger.logD(CLASS_TAG, "mLoadingDialog != null: "
                            + (mLoadingDialog != null));
                    if (mLoadingDialog != null) {
                        mLoadingDialog.cancel();
                    }
                    break;

                default:
                    break;
                }
            }
        };
    }

    private void startScanFiles() {
        if (mLoadingDialog == null) {
            initLoadingDialog();
        }
        mLoadingDialog.show();

        if (mFileScanner == null) {
            mFileScanner = new BackupFileScanner(getActivity(), mHandler);
        } else {
            mFileScanner.setHandler(mHandler);
        }
        MyLogger.logI(CLASS_TAG, "RestoreTabFragment: startScanFiles");
        mFileScanner.startScan();
    }

    @SuppressWarnings("unchecked")
    private void addScanResultsAsPreferences(Object obj) {

        PreferenceScreen ps = getPreferenceScreen();

        // clear the old items last scan
        ps.removeAll();
        mRecordNum = 0;
        if (obj == null) {
            return;
        }

        HashMap<String, List<BackupFilePreview>> map =
                (HashMap<String, List<BackupFilePreview>>) obj;
        Preference noDataPreference = new Preference(getActivity());
        noDataPreference.setTitle("No Record");
        boolean noRecord = true;
        // personal data
        List<BackupFilePreview> items = map.get(Constants.SCAN_RESULT_KEY_PERSONAL_DATA);
        if (items != null && !items.isEmpty()) {
        	//D HIOSWY-2979 by huan.yang 20151123 @{
            //noRecord = false;
            //D HIOSWY-2979 by huan.yang 20151123 @}
            boolean flag = false;
            for (BackupFilePreview item : items) {
            	//M HIOSWY-2979 by huan.yang 20151123 @{
            	if(item.ismIsNormalEnd()){
            		flag = true; 
            		noRecord = false;
            		break;
            	}else{
            		noRecord = true;
            	}
            	//M HIOSWY-2979 by huan.yang 20151123 @}
            }
            if(flag){
            	addPreferenceCategory(ps, R.string.backup_personal_data_history);
                for (BackupFilePreview item : items) {
                    addRestoreCheckBoxPreference(ps, item, "personal data");
                }
            }
        }

        // app data
        items = map.get(Constants.SCAN_RESULT_KEY_APP_DATA);
        if (items != null && !items.isEmpty()) {
            addPreferenceCategory(ps, R.string.backup_app_data_history);
            noRecord = false;
            for (BackupFilePreview item : items) {
                addRestoreCheckBoxPreference(ps, item, "app");
            }
        }
        if (noRecord) {
            MyLogger.logD(CLASS_TAG, "getActivity = " + getActivity());
            if (mEmptyView != null) {
                mEmptyView.setText(R.string.no_data);
            }
            // ps.addPreference(noDataPreference);
        }

        if (mDeleteActionMode && mActionModeListener != null) {
            MyLogger.logD(CLASS_TAG, " confirmSyncCheckedPositons now!!!");
            mActionModeListener.confirmSyncCheckedPositons();
        }
    }

    private void addPreferenceCategory(PreferenceScreen ps, int titleId) {
        PreferenceCategory category = new PreferenceCategory(getActivity());
        category.setTitle(titleId);
        ps.addPreference(category);
    }

    private void addRestoreCheckBoxPreference(PreferenceScreen ps, BackupFilePreview item,
            String type) {
        if (item == null || type == null) {
            MyLogger.logE(CLASS_TAG, "addRestoreCheckBoxPreference: Error!");
            return;
        }
        if(!item.ismIsNormalEnd()){
        	return;
        }
        RestoreCheckBoxPreference preference = new RestoreCheckBoxPreference(getActivity());
        if (type.equals("app")) {
            preference.setTitle(R.string.backup_app_data_preference_title);
        } else {
            String fileName = item.getFileName();
            preference.setTitle(fileName);
        }
        MyLogger.logI(CLASS_TAG, "addRestoreCheckBoxPreference: type is " + type + " fileName = "
                + item.getFileName());
        StringBuilder builder = new StringBuilder(getString(R.string.backup_data));
        builder.append(" ");
        builder.append(FileUtils.getDisplaySize(item.getFileSize(), getActivity()));
        preference.setRestored(item.isRestored());
        preference.setSummary(builder.toString());
        if (mDeleteActionMode) {
            preference.showCheckbox(true);
        }
        preference.setAccociateFile(item.getFile());

        Intent intent = new Intent();
        if (type.equals("app")) {
            intent.setClass(getActivity(), AppRestoreActivity.class);
        } else {
            intent.setClass(getActivity(), PersonalDataRestoreActivity.class);
        }
        intent.putExtra(Constants.FILENAME, item.getFile().getAbsolutePath());
        preference.setIntent(intent);
        ps.addPreference(preference);
        mRecordNum ++ ;
    }

    private void showCheckBox(boolean bShow) {
        PreferenceScreen ps = getPreferenceScreen();
        int count = ps.getPreferenceCount();
        for (int position = 0; position < count; position++) {
            Preference p = ps.getPreference(position);
            if (p instanceof RestoreCheckBoxPreference) {
                ((RestoreCheckBoxPreference) p).showCheckbox(bShow);
            }
        }
    }

    public boolean showDeleteMenu(final boolean flag){
    	if(mMenuBar == null || mFooterButton == null){
    		return false;
    	}
    	mDeleteActionMode = flag;
    	showCheckBox(mDeleteActionMode);
    	final int height = mMenuBar.getHeight();
    	final int fbHeight = mFooterButton.getHeight()+mFooterButton.getBottom();
    	PropertyValuesHolder panelAlpha = null;
    	PropertyValuesHolder panelDriftY = null;
    	PropertyValuesHolder fbPanelDriftY = null;
    	if(flag){
    		mMenuBar.setVisibility(View.VISIBLE);
    		panelAlpha = PropertyValuesHolder.ofFloat("alpha", 0, 1f);
            panelDriftY = PropertyValuesHolder.ofFloat("translationY", -height, 0);
            fbPanelDriftY = PropertyValuesHolder.ofFloat("translationY", fbHeight, 0);
            if(mActionModeListener != null){
				mActionModeListener.enterDeleteMenuMode();
			}
            if(mFooterButton != null){
            	mFooterButton.setVisibility(View.VISIBLE);
            	mFooterFL.setVisibility(View.VISIBLE);
            }
            if(mEmptyFooterGroupView != null){
            	getListView().addFooterView(mEmptyFooterGroupView,null,false);
            }
    	} else {
    		panelAlpha = PropertyValuesHolder.ofFloat("alpha", 1, 0f);
            panelDriftY = PropertyValuesHolder.ofFloat("translationY", 0, -height);
            fbPanelDriftY = PropertyValuesHolder.ofFloat("translationY", 0, fbHeight);
            if(mActionModeListener != null){
				mActionModeListener.exitDeleteMenuMode();
			}
            if(mEmptyFooterGroupView != null){
            	 getListView().removeFooterView(mEmptyFooterGroupView);
            }
    	}
    	
    	ObjectAnimator panelAlphaAndDrift = ObjectAnimator.ofPropertyValuesHolder(mMenuBar,
                panelAlpha, panelDriftY);
    	ObjectAnimator fbPanelAlphaAndDrift = ObjectAnimator.ofPropertyValuesHolder(mFooterFL,
                panelAlpha, fbPanelDriftY);
    	panelAlphaAndDrift.addListener(new AnimatorListenerAdapter() {
    		@Override
    		public void onAnimationEnd(Animator animation) {
    			if(!flag){
    				mMenuBar.setVisibility(View.INVISIBLE);
    			}
    			super.onAnimationEnd(animation);
    		}
    		
    		@Override
    		public void onAnimationCancel(Animator animation) {
    			if(!flag){
    				mMenuBar.setVisibility(View.INVISIBLE);
    			}
    			super.onAnimationCancel(animation);
    		}
		});
    	fbPanelAlphaAndDrift.addListener(new AnimatorListenerAdapter() {
    		@Override
    		public void onAnimationEnd(Animator animation) {
    			if(!flag){
    	            mFooterButton.setVisibility(View.INVISIBLE);
    	            mFooterFL.setVisibility(View.INVISIBLE);
    			}
    			super.onAnimationEnd(animation);
    		}
    		
    		@Override
    		public void onAnimationCancel(Animator animation) {
    			if(!flag){
    	            mFooterButton.setVisibility(View.INVISIBLE);
    	            mFooterFL.setVisibility(View.INVISIBLE);
    			}
    			super.onAnimationCancel(animation);
    		}
		});
        panelAlphaAndDrift.setDuration(300);
        panelAlphaAndDrift.setInterpolator(new DecelerateInterpolator());
        fbPanelAlphaAndDrift.setDuration(300);
        fbPanelAlphaAndDrift.setInterpolator(new DecelerateInterpolator());
        panelAlphaAndDrift.start();
        fbPanelAlphaAndDrift.start();
        return true;
    }
    
    private Dialog mDeleteAffirmDialog;
    
	class DeleteMenuMode implements OnClickListener{
    	
    	private int mCheckedCount;
        private HashSet<String> mCheckedItemIds;
        
        public DeleteMenuMode() {
		}
        
        public void enterDeleteMenuMode(){
        	mListView.setLongClickable(false);
        	//A HIOSWY-3306 by huan.yang 20151119 @{ 
            if(mFooterFL!=null){
            	mFooterFL.setClickable(true);
            }
            //A HIOSWY-3306 by huan.yang 20151119 @}
        	mCheckedItemIds = new HashSet<String>();
            setAllItemChecked(false);
            showCheckBox(true);
        }
        
        public void exitDeleteMenuMode(){
        	mListView.setLongClickable(true);
        	mCheckedItemIds = null;
            mCheckedCount = 0;
            showCheckBox(false);
        }
        
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.menu_action_back_ll:
			    //M HIOSWY-5985 HIOSWY-5984 by huan.yang 20160104 @{
			    if(mDeleteAffirmDialog!=null&&!mDeleteAffirmDialog.isShowing()){
				showDeleteMenu(false);
			    }else if(mDeleteAffirmDialog==null){
			        showDeleteMenu(false);
			    }
			    //@}
				break;
			case R.id.menu_all_select_box:
			    CheckBox checkBox = (CheckBox)v;
			    if(mCheckedItemIds!=null){ //A HIOSWY-5984 by huan.yang 20160113
			        if(checkBox.isChecked()){
			            setAllItemChecked(true);
			        } else {
			            setAllItemChecked(false);
			        }
			    }
			    break;
			case R.id.menu_trash_button:
				if (mCheckedCount == 0) {
                    Toast.makeText(getActivity(), R.string.no_item_selected, Toast.LENGTH_SHORT)
                            .show();
                } else {
                    startDeleteItems(mCheckedItemIds);
                    showDeleteMenu(false);
                }
				break;
			case R.id.backup_bt_backcup:
				if (mCheckedCount == 0) {
                    Toast.makeText(getActivity(), R.string.no_item_selected, Toast.LENGTH_SHORT)
                            .show();
                } else {
                	if(mDeleteAffirmDialog == null){
                		mDeleteAffirmDialog = new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.warning).setMessage(R.string.delete_confirm)
                        //M HIOSWY-4341 by huan.yang 20151204 @{
                        .setPositiveButton(R.string.menu_delete, new DialogInterface.OnClickListener() {
                         //@}
                        	@Override
                            public void onClick(final DialogInterface arg0, final int arg1) {
                            	startDeleteItems(mCheckedItemIds);
                                showDeleteMenu(false);
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface arg0, final int arg1) {
                            }
                        }).setCancelable(true).create();
                		//M HIOSWY-2962 by huan.yang 20151113 @{
                		mDeleteAffirmDialog.setOnShowListener(new DialogInterface.OnShowListener() {
							
							@Override
							public void onShow(DialogInterface dialog) {
								// TODO Auto-generated method stub
								((Button)mDeleteAffirmDialog.getWindow().findViewById(android.R.id.button1))
								.setTextColor(0xffff0000);
								
							}
						});
                		//M HIOSWY-2962 by huan.yang 20151113 @}
                		mDeleteAffirmDialog.show();
                	} else {
                		mDeleteAffirmDialog.show();
                	}
                }
				break;
			default:
				break;
			}
		}
    	
		private void updateTitle() {
            StringBuilder builder = new StringBuilder();
            //M HIOSWY-2973 by huan.yang 20151113@{            
            builder.append(mCheckedCount);
            builder.append(" ");
            builder.append(getString(R.string.selected));            
          //M HIOSWY-2973 by huan.yang 20151113@} 
            if(mMenuSelectItems != null){
            	mMenuSelectItems.setText(builder.toString());
            	MyLogger.logI(CLASS_TAG,
                        "updateTitle() titleString : " + builder.toString()+",mRecordNum="+mRecordNum);
            }
            if(mCheckedCount < mRecordNum){
            	mMenuSelectCheckBox.setChecked(false);
            } else {
            	mMenuSelectCheckBox.setChecked(true);
            }
            updateFooterButton();//A HIOSWY-5384 by huan.yang 20151218
        }
		//A HIOSWY-5384 by huan.yang 20151218 @{
        private void updateFooterButton(){
        	if(mCheckedCount>0){
        		mFooterButton.setAlpha(1f);
        	}else{
        		mFooterButton.setAlpha(0.7f);
        	}
        }
        //@}
        public void onPreferenceItemClick(PreferenceScreen ps, final int position) {
            Preference preference = ps.getPreference(position);
            if (preference instanceof RestoreCheckBoxPreference) {
                RestoreCheckBoxPreference p = (RestoreCheckBoxPreference) preference;
                boolean toChecked = !p.isChecked();
                p.setChecked(toChecked);
                String key = p.getAccociateFile().getAbsolutePath();
                if (toChecked) {
                    mCheckedItemIds.add(key);
                    mCheckedCount++;
                } else {
                    mCheckedItemIds.remove(key);
                    mCheckedCount--;
                }
                updateTitle();
            }
        }

        public void setItemChecked(final RestoreCheckBoxPreference p, final boolean checked) {
            if (p.isChecked() != checked) {
                p.setChecked(checked);
                String key = p.getKey();
                if (checked) {
                    mCheckedItemIds.add(key);
                    mCheckedCount++;
                } else {
                    mCheckedItemIds.remove(key);
                    mCheckedCount--;
                }
            }
            updateTitle();
        }

        private void setAllItemChecked(boolean checked) {
            PreferenceScreen ps = getPreferenceScreen();

            mCheckedCount = 0;
            mCheckedItemIds.clear();
            int count = ps.getPreferenceCount();
            for (int position = 0; position < count; position++) {
                Preference preference = ps.getPreference(position);
                if (preference instanceof RestoreCheckBoxPreference) {
                    RestoreCheckBoxPreference p = (RestoreCheckBoxPreference) preference;
                    p.setChecked(checked);
                    if (checked) {
                        mCheckedItemIds.add(p.getAccociateFile().getAbsolutePath());
                        mCheckedCount++;
                    }
                }
            }
            updateTitle();
        }

        /**
         * @return
         * after refreshed, must sync witch mCheckedItemIds;
         */
        public void confirmSyncCheckedPositons() {
            mCheckedCount = 0;

            HashSet<String> tempCheckedIds = new HashSet<String>();
            PreferenceScreen ps = getPreferenceScreen();
            int count = ps.getPreferenceCount();
            for (int position = 0; position < count; position++) {
                Preference preference = ps.getPreference(position);
                if (preference instanceof RestoreCheckBoxPreference) {
                    RestoreCheckBoxPreference p = (RestoreCheckBoxPreference) preference;
                    String key = p.getAccociateFile().getAbsolutePath();
                    if (mCheckedItemIds.contains(key)) {
                        tempCheckedIds.add(key);
                        p.setChecked(true);
                        mCheckedCount++;
                    }
                }
            }
            mCheckedItemIds.clear();
            mCheckedItemIds = tempCheckedIds;
            updateTitle();
        }

        public void saveState(final Bundle outState) {
            ArrayList<String> list = new ArrayList<String>();
            for (String item : mCheckedItemIds) {
                list.add(item);
            }
            outState.putStringArrayList(STATE_CHECKED_ITEMS, list);
        }

        public void restoreState(Bundle state) {
            ArrayList<String> list = state.getStringArrayList(STATE_CHECKED_ITEMS);
            if (list != null && !list.isEmpty()) {
                for (String item : list) {
                    mCheckedItemIds.add(item);
                }
            }
            PreferenceScreen ps = getPreferenceScreen();
            if (ps.getPreferenceCount() > 0) {
                confirmSyncCheckedPositons();
            }
        }        
    }
    
    /**
     * @author mtk81330
     *
     */
    private class DeleteCheckItemTask extends AsyncTask<HashSet<File>, String, Long> {

        private ProgressDialog mDeletingDialog;
      //rlk delete meng.wu WSHBLL-1229 20160413 (start)
        public DeleteCheckItemTask() {
//            mDeletingDialog = new ProgressDialog(getActivity());
//            mDeletingDialog.setCancelable(false);
//            mDeletingDialog.setMessage(getString(R.string.delete_please_wait));
//            mDeletingDialog.setIndeterminate(true);
        }
        //rlk delete meng.wu WSHBLL-1229 20160413 (end)

        @Override
        protected void onPostExecute(Long arg0) {
            super.onPostExecute(arg0);
            Activity activity = getActivity();
            if (activity != null) {
                startScanFiles();
            }
            if (activity != null && mDeletingDialog != null) {
                mDeletingDialog.dismiss();
            }
        }

        @Override
        protected void onPreExecute() {
            Activity activity = getActivity();
            if (activity != null && mDeletingDialog != null) {
                mDeletingDialog.show();
            }
        }

        @Override
        protected Long doInBackground(HashSet<File>... params) {
            HashSet<File> deleteFiles = params[0];
            for (File file : deleteFiles) {
                FileUtils.deleteFileOrFolder(file, getActivity());
            }
            return null;
        }
    }

    /**
     * @return ActionMode.
     */
    public boolean getDeleteMode() {
        return mDeleteActionMode;
    }    
}
